<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/26
 * Time: 16:49
 */
namespace app\admin\service;

use app\admin\model\SysAreaModel;
use app\admin\model\SysCityModel;
use app\admin\model\SysDistrictModel;
use app\admin\model\SysProvinceModel;
use think\Db;
use think\Cache;
class AddressService
{
    public function getAreaList()
    {

        $cache = Cache::tag("address")->get("getAreaList");
        if(empty($cache))
        {
            $area = new SysAreaModel();
            $list = $area->getList('area_id,area_name');
            Cache::tag("address")->set("getAreaList", $list);
            return $list;
        }else{
            return $cache;
        }

        // TODO Auto-generated method stub
    }

    /**
     * @param int $area_id
     * @return array|mixed
     * 获取省列表
     */
    public function getProvinceList($area_id = 0){
        $cache = Cache::tag("address")->get("getProvinceList".$area_id);
        if(empty($cache))
        {
            $province = new SysProvinceModel();
            if ($area_id == - 1) {
                $list = array();
            } elseif ($area_id == 0) {
                $list = $province->getList( 'province_id,area_id,province_name,sort','', 'sort asc');
            } else {
                $list = $province->getList( 'province_id,area_id,province_name,sort',['area_id' => $area_id], 'sort asc');
            }
            Cache::tag("address")->set("getProvinceList".$area_id, $list);
            return $list;
        }else{
            return $cache;
        }
    }

    /**
     * @param $province_id
     * @return int|string
     * 获取该省下城市数量
     */
    public function getCityCountByProvinceId($province_id){
        $city = new SysCityModel();
        $count = $city->getCount([
            'province_id' => $province_id
        ]);
        return $count;
    }

    /**
     * @param int $province_id
     * @return false|mixed|\PDOStatement|string|\think\Collection
     * 获取城市列表
     */
    public function getCityList($province_id=0){
        $cache = Cache::tag("address")->get("getCityList".$province_id);
        if(empty($cache))
        {
            $city = new SysCityModel();
            if ($province_id == 0) {
                $list = $city->getlist( 'city_id,province_id,city_name,zipcode,sort','', 'sort asc');
            } else {
                $list = $city->getlist( 'city_id,province_id,city_name,zipcode,sort',['province_id' => $province_id], 'sort asc');
            }
            Cache::tag("address")->set("getCityList".$province_id, $list);
            return $list;
        }else{
            return $cache;
        }
    }

    /**
     * 通过市级id获取其下级的数量
     *
     */
    public function getDistrictCountByCityId($city_id)
    {
        $district = new SysDistrictModel();
        $count = $district->getCount([
            'city_id' => $city_id
        ]);
        return $count;
    }
    /**
     * 通过市级id获取其下级
     */
    public function getDistrictList($city_id=0){
        $cache = Cache::tag("address")->get("getDistrictList".$city_id);
        if(empty($cache))
        {
            $district = new SysDistrictModel();
            if ($city_id == 0) {
                $list = $district->getList( 'district_id,city_id,district_name,sort', '','sort asc');
            } else {
                $list = $district->getList( 'district_id,city_id,district_name,sort', ['city_id' => $city_id],'sort asc');
            }
            Cache::tag("address")->set("getDistrictList".$city_id, $list);
            return $list;
        }else{
            return $cache;
        }
    }
    /**
     * 添加一级区域
     */
    public function addProvince($province_name, $sort, $area_id){
        Cache::tag("address")->clear();
        $province = new SysProvinceModel();
        $data = array(
            "province_name" => $province_name,
            "sort" => $sort,
            "area_id" => $area_id
        );
        $province->save($data);
        return $province->province_id;
    }
    /**
     * 删除省级地区
     */

    public function deleteProvince($province_id){
        Cache::tag("address")->clear();
        $province = new SysProvinceModel();
        $city = new SysCityModel();
        $province->startTrans();
        try {
            $city_list = $city->getlist('city_id',[
                'province_id' => $province_id
            ], '');
            $city_list=$city_list->toArray();
            foreach ($city_list as $k => $v) {
                $this->deleteCity($v['city_id']);
            }
            $province->destroy($province_id);
            $province->commit();
            return 1;
        } catch (\Exception $e) {
            $province->rollback();
            return $e->getMessage();
        }
    }
    /**
     * 删除城市
     */
    public function deleteCity($city_id){
        Cache::tag("address")->clear();
        $city = new SysCityModel();
        $district = new SysDistrictModel();
        $city->startTrans();
        try {
            $district->destroy([
                'city_id' => $city_id
            ]);
            $city->destroy($city_id);
            $city->commit();
            return 1;
        } catch (\Exception $e) {
            $city->rollback();
            return $e->getMessage();
        }
    }
    /**
     * 删除区域
     */
    public function deleteDistrict($district_id){
        Cache::tag("address")->clear();
        $district = new SysDistrictModel();
        return $district->destroy($district_id);
    }

    /**
     * @param $city_id
     * @param $province_id
     * @param $city_name
     * @param string $zipcode
     * @param string $sort
     * @return mixed
     * 添加城市
     */
    public function addOrupdateCity($city_id, $province_id, $city_name, $zipcode = '', $sort = '')
    {
        Cache::tag("address")->clear();
        $city = new SysCityModel();
        $data = array(
            "province_id" => $province_id,
            "city_name" => $city_name,
            "zipcode" => $zipcode,
            "sort" => $sort
        );
        if ($city_id > 0 && $city_id != 0) {
            $res = $city->save($data, [
                'city_id' => $city_id
            ]);
            return $res;
        } else {
            $city->save($data);
            return $city->city_id;
        }
    }

    /**
     * @param $district_id
     * @param $city_id
     * @param $district_name
     * @param string $sort
     * @return mixed添加区域
     */
    public function addOrupdateDistrict($district_id, $city_id, $district_name, $sort = '')
    {
        Cache::tag("address")->clear();
        $district = new SysDistrictModel();
        $data = array(
            "city_id" => $city_id,
            "district_name" => $district_name,
            "sort" => $sort
        );
        if ($district_id > 0 && $district_id != 0) {
            return $district->save($data, [
                "district_id" => $district_id
            ]);
        } else {
            $district->save($data);
            return $district->district_id;
        }
    }

    /**
     * $upType 修改类型 1排序 2名称
     * $regionType 修改地区类型 1省 2市 3县
     */
    public function updateRegionNameAndRegionSort($upType, $regionType, $regionName, $regionSort, $regionId){
        Cache::tag("address")->clear();
        if ($regionType == 1) {
            $province = new SysProvinceModel();
            if ($upType == 1) {
                $res = $province->save([
                    'sort' => $regionSort
                ], [
                    'province_id' => $regionId
                ]);
                return $res;
            }
            if ($upType == 2) {
                $res = $province->save([
                    'province_name' => $regionName
                ], [
                    'province_id' => $regionId
                ]);
                return $res;
            }
        }
        if ($regionType == 2) {
            $city = new SysCityModel();

            if ($upType == 1) {
                $res = $city->save([
                    'sort' => $regionSort
                ], [
                    'city_id' => $regionId
                ]);
                return $res;
            }
            if ($upType == 2) {
                $res = $city->save([
                    'city_name' => $regionName
                ], [
                    'city_id' => $regionId
                ]);
                return $res;
            }
        }
        if ($regionType == 3) {
            $district = new SysDistrictModel();
            if ($upType == 1) {
                $res = $district->save([
                    'sort' => $regionSort
                ], [
                    'district_id' => $regionId
                ]);
                return $res;
            }
            if ($upType == 2) {
                $res = $district->save([
                    'district_name' => $regionName
                ], [
                    'district_id' => $regionId
                ]);
                return $res;
            }
        }
    }
    /**
     *修改市级信息
     */
    public function updateProvince($province_id, $province_name, $sort, $area_id)
    {
        Cache::tag("address")->clear();
        $province = new SysProvinceModel();
        $data = array(
            "province_name" => $province_name,
            "sort" => $sort,
            "area_id" => $area_id
        );
        return $province->save($data, [
            "province_id" => $province_id
        ]);
    }

    /**
     * 运费模板的数据整理
     * @param unknown $existing_address_list
     */
    public function getAreaTree_ext($district=null)
    {
        $district2=implode(',',$district);
        $cache = Cache::tag("address")->get("getAreaTree_ext".$district2);
        if (empty($cache)) {
            $list = array();
            $select_district_id_array = [];
            if($district){
                $select_district_id_array=$district;
            }

            //查询所有的地区信息
            $area_list = $this->getAreaList();
            //查询所有的省信息
            $province_list = $this->getProvinceList();
            //查询所有的市信息
            $city_list = $this->getCityList();
            //查询所有的区县的信息
            $district_list = $this->getDistrictList();

            $district_id_deal_array = [];
            //先整理所有区县的是否禁用的整理
            foreach ($district_list as $k_district => $v_district) {
                $is_set = false;
                $is_disabled = 0;
                $district_id = $v_district["district_id"];
                $district_id_deal_array[$district_id] = $k_district;
                $is_set = in_array($district_id, $select_district_id_array);
                if ($is_set) {
                    $is_disabled = 1;
                }

                $district_list[$k_district]["is_disabled"] = $is_disabled;
            }
            //整理市的集合
            foreach ($city_list as $k_city => $v_city) {
                $deal_array = $this->dealCityDistrictData($v_city["city_id"], $district_list, $district_id_deal_array);
                $child_district_array = $deal_array["child_district"];
                $is_disabled = $deal_array["is_disabled"];
                $city_list[$k_city]["district_list"] = $child_district_array;
                $city_list[$k_city]["is_disabled"] = $is_disabled;
                $city_list[$k_city]["district_list_count"] = count($child_district_array);
            }
            //整理省的集合
            foreach ($province_list as $k_province => $v_province) {
                $deal_array = $this->dealProvinceCityData($v_province["province_id"], $city_list);
                $child_city_array = $deal_array["child_city"];
                $is_disabled = $deal_array["is_disabled"];
                $province_list[$k_province]["city_list"] = $child_city_array;
                $province_list[$k_province]["is_disabled"] = $is_disabled;
                $province_list[$k_province]["city_count"] = count($child_city_array);
                $province_list[$k_province]["city_disabled_count"] = 0;
            }
            //整理地区的集合
            foreach ($area_list as $k_area => $v_area) {
                $deal_array = $this->dealAreaProvinceData($v_area["area_id"], $province_list);
                $child_province_array = $deal_array["child_province"];
                $is_disabled = $deal_array["is_disabled"];
                $area_list[$k_area]["province_list"] = $child_province_array;
                $area_list[$k_area]["is_disabled"] = $is_disabled;
                $area_list[$k_area]["province_list_count"] = count($child_province_array);
            }
            Cache::tag("address")->set("getAreaTree_ext".$district2, $area_list);
            return $area_list;
        } else {
            return $cache;
        }
    }

        /**
         * 处理市和 地区的信息
         */
        private function dealCityDistrictData($city_id, $district_list, $district_id_deal_array, $select_city_ids=[]){
            $is_disabled=1;
            $district_child_list = $this->getDistrictList($city_id);
            foreach ($district_child_list as $k=>$district_obj){
                $dis_id=$district_obj["district_id"];
                $k_num=$district_id_deal_array[$dis_id];
                $district_child_list[$k]["is_disabled"]=$district_list[$k_num]["is_disabled"];
                if($district_list[$k_num]["is_disabled"]==0){
                    $is_disabled=0;
                }
            }
            if(empty($district_child_list)){
                $is_set=in_array($city_id, $select_city_ids);
                if($is_set){
                    $is_disabled=1;
                }else{
                    $is_disabled=0;
                }
            }
            return array(
                "child_district"=>$district_child_list,
                "is_disabled"=>$is_disabled
            );
        }

        /**
         * 处理省和市的信息
         * @param unknown $province_id
         * @param unknown $city_list
         */
        private function dealProvinceCityData($province_id, $city_list, $province_id_array=[]){
        $city_child_array=[];
        $is_disabled=1;
        foreach ($city_list as $city_obj){
            if($city_obj["province_id"]==$province_id){
                $city_child_array[]=$city_obj;
                if($city_obj["is_disabled"]==0){
                    $is_disabled=0;
                }
            }
        }
        if(empty($city_child_array)){
            $is_set=in_array($province_id, $province_id_array);
            if($is_set){
                $is_disabled=1;
            }else{
                $is_disabled=0;
            }
        }
        return array(
            "child_city"=>$city_child_array,
            "is_disabled"=>$is_disabled
        );
    }
        /**
         * 处理区域的信息
         * @param unknown $area_id
         * @param unknown $province_list
         */
        private function dealAreaProvinceData($area_id, $province_list){
        $province_child_array=[];
        $is_disabled=1;
        foreach ($province_list as $province_obj){
            if($province_obj["area_id"]==$area_id){
                $province_child_array[]=$province_obj;
                if($province_obj["is_disabled"]==0){
                    $is_disabled=0;
                }
            }
        }
        return array(
            "child_province"=>$province_child_array,
            "is_disabled"=>$is_disabled
        );
    }

    public function getAddressListById($province_id_arr, $city_id_arr)
    {
        $cache = Cache::tag("address")->get("getAddressListById".$province_id_arr.'_'.$city_id_arr);
        if(empty($cache))
        {
            $province = new SysProvinceModel();
            $city = new SysCityModel();

            $province_condition = array(
                'province_id' => array(
                    'in',
                    $province_id_arr
                )
            );
            $city_condition = array(
                'city_id' => array(
                    'in',
                    $city_id_arr
                )
            );
            $province_list = $province->getModelQuery($province_condition, 'province_id,province_name', 'sort asc')->toArray();
            $city_list = $city->getModelQuery($city_condition, 'province_id,city_name,city_id', 'sort asc')->toArray();;
            foreach ($province_list as $k => $v) {
                $list['province_list'][$k] = $v;
                $children_list = array();
                foreach ($city_list as $city_k => $city_v) {
                    if ($v['province_id'] == $city_v['province_id']) {
                        $children_list[$city_k] = $city_v;
                    }
                }
                $list['province_list'][$k]['city_list'] = $children_list;
            }
            Cache::tag("address")->set("getAddressListById".$province_id_arr.'_'.$city_id_arr, $list);
            return $list;
        }else{
            return $cache;
        }

    }

    function  get_all_province(){
        $cache = Cache::tag("address")->get("new_province");
        if(empty($cache)){
            $province=$this->getProvinceList();
            $new_province=[];
            foreach($province as $key=>$value){
                $new_province[$key]=[
                    'id'=>$value['province_id'],
                    'value'=>$value['province_name']
                ];
                $new_city=[];
                $city=$this->getCityList($value['province_id']);
                foreach($city as $k=>$v){
                    $new_city[$k]=[
                        'id'=>$v['city_id'],
                        'value'=>$v['city_name']
                    ];
                    $district=$this->getDistrictList($v['city_id']);
                    $new_district=[];
                    foreach($district as $k1=>$v1){
                        $new_district[$k1]=[
                            'id'=>$v1['district_id'],
                            'value'=>$v1['district_name']
                        ];
                    }
                    $new_city[$k]['childs']=$new_district;
                }
                $new_province[$key]['childs']=$new_city;
            }
            Cache::tag("address")->set("new_province", $new_province);
            return $new_province;
        }else{
            return $cache;
        }
    }

    function get_postion_province($province_id,$city_id,$district_id){
        $province=$this->getProvinceList();
        $data['key1']=0;
        $data['key2']=0;
        $data['key3']=0;
        foreach ($province as $k=>$v){
            if($v['province_id']==$province_id){
                $data['key1']=$k;
            }
        }
        $city=$this->getCityList($province_id);
        foreach ($city as $k=>$v){
            if($v['city_id']==$city_id){
                $data['key2']=$k;
            }
        }
        $district=$this->getDistrictList($city_id);
        foreach ($district as $k=>$v){
            if($v['district_id']==$district_id){
                $data['key3']=$k;
            }
        }
        return $data;
    }

}